const { createApp, reactive, ref, watch, onMounted } = Vue;
const app2 = createApp({
    setup() {
        const dpData = reactive({
            info: {
                AP: "0%",
                crowding_degree: 0,
                dp_zdf: 0,
                exponent: 0,
                is_kp: true,
            },
        });
        //const local = "http://1688.hk.cn:32100"
        const local = "http://192.168.8.5:8081";
        const jkData = reactive({
            data: [],
            columns: [],
            update_date: null,
        });
        let zxInput = ref("");
        let relitu = ref();
        const bkData = reactive({
            data: [],
        });

        let searchInput = ref("");
        watch(searchInput, (newVal, oldVal) => {
            currentType.name = "自选";
            if (newVal == "") {
                currentType.uri = `zxData/all`;
            } else {
                currentType.uri = `zxData/all?value=${newVal}`;
            }
        });

        const currentType = reactive({
            name: "涨速",
            uri: "zsData",
        });
        let currentSortIndex = ref(5);
        function get_data(uri) {
            axios.defaults.timeout = 1000 * 15;
            axios.defaults.headers.common[
                "Authorization"
            ] = `${localStorage.getItem("access_token")}`;
            return axios.get(`${local}/${uri}`);
        }
        /**
         * 切换窗口
         * @param {string} name 切换窗口名
         * @param {string} uri uri后缀
         */
        function toggle(name, uri) {
            jkData.data = [];
            currentType.name = name;
            currentType.uri = uri;
            get_data(currentType.uri).then((res) => {
                let data = res["data"]["response"];
                jkData.update_date = data.update_date;
                if (res["data"].code == 200) {
                    if (data) {
                        data = JSON.parse(data["data"]);
                    }
                    jkData.columns = Object.keys(data[0]);
                } else {
                    jkData.data = [];
                    jkData.update_date = "请求错误";
                }
            });
            if (name == "热力图") {
                setChartOption(myChart, rltData);
            }
        }

        /**
         * 更新热力图10秒一次
         */
        // setInterval(() => {
        //     setChartOption(myChart, rltData)
        // }, 1000*5)

        /**
         * 请求当前窗口的数据
         */
        function requestCurrentData() {
            setTimeout(() => {
                get_data(currentType.uri)
                    .then((res) => {
                        let data = res["data"]["response"];
                        jkData.update_date = data.update_date;
                        if (data) {
                            data = JSON.parse(data["data"]);
                        }

                        jkData.columns = Object.keys(data[0]);
                        if (res["data"].code == 200) {
                            jkData.data = data;
                            jkData.data.sort((x, y) => {
                                let index = 0;
                                let column = "";
                                if (currentSortIndex.value < 0) {
                                    let index = -currentSortIndex.value;

                                    column = jkData.columns[index];
                                    return x[column] - y[column];
                                }
                                index = currentSortIndex.value;
                                column = jkData.columns[index];
                                return y[column] - x[column];
                            });

                            if (currentType.name == "热力图") {
                                rltData = [];
                                for (let i = 0; i < jkData.data.length; i++) {
                                    computedVal(7, jkData.data[i], 1);
                                    let stockBkNames = JSON.parse(items[index]);
                                    let filterBkData = bkData["data"].slice(
                                        0,
                                        10
                                    );
                                    putRlt(
                                        stockBkNames[b_index],
                                        filterBkData[i][2].toFixed(2),
                                        items
                                    );
                                }
                                rltData = rltData.filter((item) => {
                                    if (!item["children"]) {
                                        return false;
                                    }
                                    return item.children.length > 1;
                                });
                            }
                        } else {
                            jkData.data = [];
                            jkData.update_date = "请求错误";
                        }
                        requestCurrentData();
                    })
                    .catch((err) => {
                        console.log(err);
                        requestCurrentData();
                    });
            }, 1000);
        }
        /**
         * 请求板块数据
         */
        function requestBkData() {
            setTimeout(() => {
                get_data("bkData")
                    .then((res) => {
                        if (res["data"].code == 200) {
                            let data = res["data"]["response"];
                            data = JSON.parse(JSON.stringify(data));
                            bkData.data = data.data;
                        }
                        requestBkData();
                    })
                    .catch((err) => {
                        console.log(err);
                        requestBkData();
                    });
            }, 5000);
        }
        /**
         * 请求大盘数据
         */
        function requestDpData() {
            setTimeout(() => {
                get_data("dpData")
                    .then((res) => {
                        if (res["data"].code == 200) {
                            let data = res["data"]["response"]["data"];
                            dpData.info = JSON.parse(JSON.stringify(data));
                        }
                        requestDpData();
                    })
                    .catch((err) => {
                        console.log(err);
                        requestDpData();
                    });
            }, 5000);
        }

        /**
         * 初始化数据
         */
        function init() {
            console.log("初始化");
            toggle(currentType.name, currentType.uri);
            bkData.data = [];
            jkData.data = [];
            requestDpData();
            requestBkData();
            requestCurrentData();
        }
        init();
        //创建复制窗口
        let copyIframe = document.createElement("iframe");
        copyIframe.id = "xpathCopyIframe";
        copyIframe.style.height = "0px";
        copyIframe.style.width = "0px";
        let input = document.createElement("textarea");
        input.id = "xpathCopyInput";
        input.style.height = "0px";
        input.style.width = "0px";

        document.body.appendChild(copyIframe);
        console.log("添加");
        let iframeBody =
            document.querySelector("#xpathCopyIframe").contentDocument.body;
        iframeBody.appendChild(input);

        //创建置顶按钮
        window.onscroll = function () {
            scrollFunction();
        };

        /**
         * 显示|隐藏 置顶按钮
         */
        function scrollFunction() {
            if (
                document.body.scrollTop > 20 ||
                document.documentElement.scrollTop > 20
            ) {
                document.getElementById("myBtn").style.display = "block";
            } else {
                document.getElementById("myBtn").style.display = "none";
            }
        }

        /**
         * 置顶函数
         */
        function topFunction() {
            document.body.scrollTop = 0;
            document.documentElement.scrollTop = 0;
        }

        /**
         * echars函数
         * @returns
         */
        function getLevelOption() {
            return [
                {
                    itemStyle: {
                        borderWidth: 0,
                        gapWidth: 5,
                    },
                },
                {
                    itemStyle: {
                        gapWidth: 1,
                    },
                },
                {
                    colorSaturation: [0.35, 0.5],
                    itemStyle: {
                        gapWidth: 1,
                        borderColorSaturation: 0.6,
                    },
                },
            ];
        }

        let rltData = [];
        let myChart = null;
        /**
         * 初始化热力图
         */
        onMounted(() => {
            myChart = echarts.init(relitu.value, null, {
                renderer: "canvas",
                useDirtyRect: false,
            });

            myChart.showLoading();
            myChart.hideLoading();
            setChartOption(myChart, rltData);

            window.addEventListener("resize", myChart.resize);
        });

        /**
         * 加载热力图配置
         * @param {*} myChart
         * @param {*} rltData
         */
        function setChartOption(myChart, rltData) {
            const formatUtil = echarts.format;
            myChart.setOption(
                (option = {
                    title: {
                        text: "",
                        left: "center",
                    },
                    textStyle: {
                        fontWeight: "bolder",
                        overflow: "break",
                        fontSize: 15,
                        width: 100,
                    },
                    tooltip: {
                        formatter: function (info) {
                            let value = info.value;
                            let children = info.data.children;
                            var treePathInfo = info.treePathInfo;
                            let treePath = [];
                            for (let i = 1; i < treePathInfo.length; i++) {
                                treePath.push(treePathInfo[i].name);
                            }
                            let bkName = "平均涨跌幅";
                            if (treePathInfo.length == 3) {
                                bkName = treePathInfo[1].name;
                                value = treePathInfo[1].value;
                            } else if (treePathInfo.length == 1) {
                                value = (
                                    treePathInfo[0].value / children.length
                                ).toFixed(2);
                            }
                            result = [
                                '<div class="tooltip-title">' +
                                    treePathInfo[treePathInfo.length - 1].name +
                                    "</div>",
                                `${bkName}: ${value}%`,
                            ].join("");
                            return result;
                        },
                    },
                    series: [
                        {
                            name: "热点图",
                            left: "center",
                            top: 100,
                            type: "treemap",
                            visibleMin: 300,
                            label: {
                                show: true,
                                formatter: "{b}",
                            },
                            itemStyle: {
                                borderColor: "#fff",
                            },
                            levels: getLevelOption(),
                            data: rltData,
                        },
                    ],
                })
            );

            if (option && typeof option === "object") {
                myChart.setOption(option);
            }
        }

        /**
         * 新增热力图数据
         * @param {*} bkName
         * @param {*} bkZdf
         * @param {*} items
         */
        function putRlt(bkName, bkZdf, items) {
            let index = rltData.findIndex((item) => {
                return item.name == bkName;
            });
            if (index < 0) {
                rltData.push({
                    name: bkName,
                    value: Number(bkZdf),
                    path: bkName,
                    children: [
                        {
                            name: `${items[0]}\n${items[3].toFixed(
                                2
                            )}%\n${items[8].toFixed(2)}`,
                            value: items[3],
                            path: `${bkName}/${items[0]}`,
                        },
                    ],
                });
            } else {
                rltData[index].value = Number(bkZdf);
                let children = rltData[index].children;
                let c_index = children.findIndex((item) => {
                    return (
                        item.name ==
                        `${items[0]}\n${items[3].toFixed(
                            2
                        )}%\n${items[8].toFixed(2)}`
                    );
                });
                if (c_index < 0) {
                    children.push({
                        name: `${items[0]}\n${items[3].toFixed(
                            2
                        )}%\n${items[8].toFixed(2)}`,
                        value: Number(items[3]),
                        path: `${bkName}/${items[0]}`,
                    });
                } else {
                    try {
                        children[c_index].value = Number(items[3]);
                    } catch (err) {
                        console.log(children[index]);
                    }
                }
            }
        }

        function padLeftZero(str) {
            return ("00" + str).substr(str.length);
        }

        /**
         * 格式化时间
         * @param {Date} date 时间
         * @param {string} fmt 格式化字符串
         * @returns {string} 格式化后的时间字符串
         */
        function formatDate(date, fmt) {
            //获取年份
            if (/(y+)/.test(fmt)) {
                // 把数字变成字符串
                let dateY = date.getFullYear() + "";
                //RegExp.$1 在判断中出现过，且是括号括起来的，所以 RegExp.$1 就是 "yyyy"
                fmt = fmt.replace(
                    RegExp.$1,
                    dateY.substr(4 - RegExp.$1.length)
                );
            }

            //获取其他
            let o = {
                "M+": date.getMonth() + 1,
                "d+": date.getDate(),
                "h+": date.getHours(),
                "m+": date.getMinutes(),
                "s+": date.getSeconds(),
            };
            for (const k in o) {
                if (new RegExp(`(${k})`).test(fmt)) {
                    let str = o[k] + "";
                    fmt = fmt.replace(
                        RegExp.$1,
                        RegExp.$1.length == 1 ? str : padLeftZero(str)
                    );
                }
            }
            return fmt;
        }

        /**
         * 切换当前窗口的class样式
         * @param {string} name 当前的窗口名
         * @returns
         */
        function isActive(name) {
            if (name === currentType.name) {
                return "nav_active";
            }
        }

        /**
         * 设置属性的颜色
         * @param {string} name 设置的属性名
         * @param {string} value 属性值
         * @param {string} data_type 数据的类型
         * @returns {string} 字体颜色的样式
         */
        function setFontColor(name, value, data_type) {
            // 今量比
            if (name == "主力资金") {
                if (value > 0.5) {
                    return "zdfBig";
                }
            }
            if (name == "换手率") {
                let val = Number(value);
                if (data_type == "wc" && val >= 5) {
                    return "middle";
                } else if (data_type == "bk" && val >= 2) {
                    return "middle";
                }
            }
            if (name == "涨跌幅" || name == "领涨股票-涨跌幅") {
                let val = Number(value);
                if (data_type == "wc" && val >= 2) {
                    return "zdfBig";
                } else if (data_type == "bk" && val >= 1) {
                    return "zdfBig";
                }
            }
            if (name == "领涨股票-涨跌幅") {
                let val = Number(value);
                if (val >= 2) {
                    return "zdfBig";
                }
            }
            let remark = "";
            if (value) {
                remark = value + "";
            }

            if (name == "涨跌幅" || name == "领涨股票-涨跌幅") {
                let val = Number(value);
                if (val < 0) {
                    return "zdfSmall";
                }
            }
            if (name == "涨速") {
                let val = Number(value);
                if (val >= 2) {
                    return "zdfBig";
                }
            }
            if (name == "指数") {
                if (value > 0) {
                    return "zdfBig";
                } else {
                    return "zdfSmall";
                }
            }
            if (value == "是") {
                return "zdfBig";
            } else if (value == "否") {
                return "zdfSmall";
            }
            return null;
        }

        /**
         * 设置列的背景色
         * @param {string} bkName 板块名称
         * @param {string} stockName 股票名称
         * @returns {string} 颜色class样式
         */
        function setBackgroundColor(bkName, stockName) {
            if (bkData["data"]) {
                let filterBkData = bkData["data"].slice(0, 10);
                for (let i = 0; i < filterBkData.length; i++) {
                    let bkZdf = Number(filterBkData[i][2]);
                    let lzgZdf = Number(filterBkData[i][7]);
                    //领涨股
                    let lzgName = filterBkData[i][6];
                    if (bkName.includes(filterBkData[i][0])) {
                        // 行业板块大于1
                        if (bkZdf >= 2) {
                            return "yellow";
                        }
                    } else if (stockName == lzgName) {
                        return "pink";
                    }
                }
            }
        }

        /**
         * 获取数据集的高度
         * @param {Array} data 数据即
         * @returns {Number} 高度
         */
        function getHeight(data) {
            if (data == null || data.length == 0) {
                return "height: 500px";
            } else {
                let len = Object.keys(data).length * 46 + 25;
                return `height: ${len}px`;
            }
        }

        /**
         * 对展示的值做处理
         * @param {number} index 下标
         * @param {Array} items 一列的数据
         * @returns {string} 处理后的值
         */
        function computedVal(hyData) {
            try {
                if (hyData == "") {
                    return "";
                }
                //
                if (hyData == "行业未更新") {
                    return "行业未更新";
                }
                let stockBkNames = JSON.parse(hyData);
                //遍历当天涨幅较大的行业
                let filterBkData = bkData.data.slice(0, 10);
                for (let i = 0; i < filterBkData.length; i++) {
                    let bkName = filterBkData[i][0];
                    if (bkName.includes("昨日")) {
                        continue;
                    }
                    if (stockBkNames == null) {
                        return "";
                    }
                    let b_index = stockBkNames.indexOf(bkName);
                    if (b_index > -1) {
                        return (
                            stockBkNames[b_index] +
                            `*${filterBkData[i][2].toFixed(2)}%`
                        );
                    }
                }
                return stockBkNames[0];
            } catch (err) {
                console.log(err);
                console.log(items);
            }
            return items[index];
        }

        /**
         * 对于部分列进行隐藏
         * @param {下标} index
         * @returns
         */
        function hidden(name) {
            if (name == "论股") {
                return false;
            }
            if (currentType.name.includes("自选")) {
                if (name == "代码") {
                    return true;
                }
            }
            return true;
        }
        /**
         * 排序
         * @param {下标} index
         */
        function setSortCfg(index) {
            if (currentSortIndex.value == index) {
                currentSortIndex.value = -index;
            } else {
                currentSortIndex.value = index;
            }
        }

        /**
         * 设置标题颜色
         * @param {下标} index
         * @returns
         */
        function setTitleColor(index) {
            if (currentSortIndex.value == index) {
                return "zdfBig";
            }
            if (-currentSortIndex.value == index) {
                return "zdfSmall";
            }
            return "";
        }

        /**
         * 复制股票代码
         * @param {string} text 文本
         */
        function copyCode(text) {
            console.log(text);
            let iframeDocument =
                document.querySelector("#xpathCopyIframe").contentDocument;

            input = iframeDocument.querySelector("#xpathCopyInput");
            input.value = text;
            input.select();
            iframeDocument.execCommand("copy") &&
                iframeDocument.execCommand("copy");
        }

        /**
         * 导出当前股票代码
         */
        function exportStock() {
            let stockList = [];
            jkData.data.forEach((item) => {
                stockList.push(item[1]);
            });
            copyCode(stockList.join(","));
        }

        /**
         * 编辑备注
         * @param {Event} event js双击事件
         * @param {number} zdf 涨跌幅
         * @param {number} dzj 大资金
         * @param {string} code 股票代码
         * @param {number} index 下标
         * @param {string} text 当前的备注
         */
        function editRemark(event, zdf, dzj, code, index, text) {
            if (!text) {
                text = "";
            }
            let value = event.target.innerText;

            let inputId = "input" + event.target.id;
            if (value == "" && index == "9") {
                if (Number(zdf) > 9.5) {
                    value = "首板";
                } else {
                    value = "昨日大资金" + Number(dzj).toFixed(2);
                }
            }

            event.target.innerHTML = `<input style="width:200px" id='${inputId}' value='${value}'></input>`;
            var input = document.getElementById(inputId);
            var td = document.getElementById(event.target.id);
            input.focus();
            // input.onblur = function () {
            //     td.innerHTML = input.value;
            //     axios.get(
            //         `${local}/updateZxData?remark=${input.value}&code=${code}`
            //     );
            // };
            input.onkeydown = function (e) {
                if (e.keyCode == 13) {
                    td.innerHTML = input.value;
                    let remark = "";
                    if (index == 9) {
                        remark = `${input.value}：${text}`;
                    } else {
                        remark = `${text}：${input.value}`;
                    }
                    axios.get(
                        `${local}/updateZxData?remark=${remark}&code=${code}`
                    );
                }
            };
        }

        /**
         * 删除自选
         * @param {string} code 股票代码
         * @param {number} index 需要删除列的当前下标
         */
        function deleteZx(code, index) {
            jkData["data"].splice(index, 1);
            axios.get(`${local}/delZxData?code=${code}`);
        }

        /**
         * 添加自选
         * @returns
         */
        function addZx() {
            let value = zxInput.value;
            console.log(value);
            if (!value) {
                return;
            }
            axios.get(`${local}/addZxData?code=${value}`);
            zxInput.value = "";
            init();
        }

        /**
         * 双击触发方法
         * @param {Event} event 双击事件
         * @param {number} index 下标
         * @param {number} zdf 涨跌幅
         * @param {number} dzj 大资金
         * @param {string} code 股票代码
         * @param {string} text 当前备注
         */
        function dbClick(event, index, zdf, dzj, code, text) {
            if (index == "9" || index == "10") {
                editRemark(event, zdf, dzj, code, index, text);
            } else {
                copyCode(code);
            }
        }

        return {
            exportStock,
            topFunction,
            setTitleColor,
            setSortCfg,
            copyCode,
            addZx,
            deleteZx,
            toggle,
            dbClick,
            hidden,
            computedVal,
            setBackgroundColor,
            getHeight,
            setFontColor,
            isActive,
            formatDate,
            relitu,
            searchInput,
            zxInput,
            currentSortIndex,
            dpData,
            bkData,
            jkData,
            currentType,
        };
    },
});
app2.mount("#app");
